import pyautogui
import time
import os
import random
from PIL import ImageGrab, Image, ImageDraw

# 配置信息
USERNAME = "pythonBluel"
PASSWORD = "your_password"
SCREENSHOT_DIR = "game_screenshots"


def switch_to_english_input():
    """切换为英文输入法"""
    try:
        # 尝试常见的输入法切换快捷键
        pyautogui.hotkey('ctrl', 'space')  # 适用于大多数中文输入法
        time.sleep(0.5)
        pyautogui.hotkey('shift')  # 额外按shift确保英文状态
        print("已切换至英文输入法")
    except Exception as e:
        print(f"输入法切换失败: {e}")


def capture_ui_elements():
    """引导用户截取界面元素用于图像识别"""
    if not os.path.exists(SCREENSHOT_DIR):
        os.makedirs(SCREENSHOT_DIR)

    elements = {
        "username_field": "用户名输入框",
        "password_field": "密码输入框",
        "login_button": "登录按钮"
    }

    print("=== 界面元素截取 ===")
    print("请按提示截取游戏界面元素(将鼠标移动到目标位置后按回车)")

    for element, desc in elements.items():
        input(f"准备截取【{desc}】...")
        time.sleep(2)

        x, y = pyautogui.position()
        region = (x - 50, y - 50, x + 50, y + 50)
        screenshot = ImageGrab.grab(region)

        template_path = os.path.join(SCREENSHOT_DIR, f"{element}.png")
        screenshot.save(template_path)
        print(f"已保存: {template_path}")


def find_element(element_name, confidence=0.8, timeout=10):
    """使用图像识别查找界面元素"""
    template_path = os.path.join(SCREENSHOT_DIR, f"{element_name}.png")
    if not os.path.exists(template_path):
        raise FileNotFoundError(f"模板图片不存在: {template_path}")

    start_time = time.time()
    while time.time() - start_time < timeout:
        try:
            location = pyautogui.locateOnScreen(template_path, confidence=confidence)
            if location:
                center = pyautogui.center(location)
                print(f"找到 {element_name} @ {center}")
                return center
        except Exception as e:
            print(f"识别出错: {e}")
        time.sleep(1)

    raise TimeoutError(f"未找到 {element_name}")


def enhanced_click(element_name, clicks=1, offset_x=0, offset_y=0):
    """增强版点击 - 带随机偏移和视觉反馈"""
    pos = find_element(element_name)
    target_x = pos.x + offset_x + random.randint(-3, 3)
    target_y = pos.y + offset_y + random.randint(-3, 3)

    pyautogui.moveTo(target_x, target_y, duration=random.uniform(0.1, 0.3))
    time.sleep(0.1)

    if os.getenv("DEBUG"):
        original = ImageGrab.grab()
        marked = original.copy()
        draw = ImageDraw.Draw(marked)
        draw.rectangle((target_x - 5, target_y - 5, target_x + 5, target_y + 5),
                       outline="red", width=2)
        marked.show()

    pyautogui.click(clicks=clicks, interval=0.1)
    time.sleep(0.5)


def game_login():
    """使用图像识别登录游戏"""
    print("=== 图像识别登录 ===")

    try:
        # 1. 定位用户名输入框
        username_pos = find_element("username_field")

        # 先切换英文输入法再点击输入框
        switch_to_english_input()
        pyautogui.click(username_pos)
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.write(USERNAME, interval=0.1)

        # 2. 定位密码输入框
        password_pos = find_element("password_field")

        # 再次确保英文输入法
        switch_to_english_input()
        pyautogui.click(password_pos)
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.write(PASSWORD, interval=0.1)

        # 3. 点击登录按钮
        for attempt in range(3):
            try:
                offset_x = random.randint(-10, 10)
                offset_y = random.randint(-10, 10)
                enhanced_click("login_button", offset_x=offset_x, offset_y=offset_y)

                time.sleep(5)
                if not pyautogui.locateOnScreen(os.path.join(SCREENSHOT_DIR, "login_button.png"), confidence=0.7):
                    print("登录成功！")
                    return True
            except:
                continue

        print("登录尝试失败")
        return False

    except Exception as e:
        print(f"登录过程中出错: {e}")
        return False


if __name__ == "__main__":
    # 首次运行需要截取界面元素
    if not os.path.exists(SCREENSHOT_DIR) or len(os.listdir(SCREENSHOT_DIR)) < 3:
        print("首次使用需要配置界面元素")
        capture_ui_elements()
        input("配置完成，按回车开始自动登录...")

    pyautogui.PAUSE = random.uniform(0.1, 0.5)

    if game_login():
        print("自动登录流程完成！")
    else:
        print("登录失败，请检查：")
        print("1. 游戏窗口是否在最前")
        print("2. 界面是否发生变化")
        print("3. 是否需要更新截图模板")